package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;
import com.situ.web.util.JDBCUtil;

public class LoginServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		//根据输入的用户名和密码去user表里面查找是不是有这个用户名和密码的用户。
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,`name`,password,age,department_id FROM `user` where `name`=? AND `password`=?";
			//预编译
			statement = connection.prepareStatement(sql);
			statement.setString(1, name);
			statement.setString(2, password);
			resultSet = statement.executeQuery();
			System.out.println(statement);
			if (resultSet.next()) {//登录成功用户存在
				int id = resultSet.getInt("id");
				String userName = resultSet.getString("name");
				String userPassword = resultSet.getString("password");
				int age = resultSet.getInt("age");
				int departmentId = resultSet.getInt("department_id");
				User user = new User(id, userName, userPassword, age, departmentId);
				//如果用户存在，将用户user对象放到Session。
				HttpSession session = req.getSession();
				session.setAttribute("user", user);
				//登录后重定向到主页
				resp.sendRedirect("/JavaWeb1905/");
			} else {//用户名密码错误
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {//不管你抛没抛出异常，finally一定会执行
			JDBCUtil.close(connection, statement, resultSet);
		}
	}
}


